#include "stack.h"

void stackInit(Stack* st)
{
	st->_a = NULL;
	st->size = st->capacity = 0;
}

void stackDestory(Stack* st)
{
	assert(st);
	assert(st->_a);
	free(st->_a);
	st->capacity = st->size = 0;
}

bool stackIsEmpty(Stack* st)
{
	assert(st);
	return st->size == 0;
}

void checkCapacity(Stack* st)
{
	assert(st);
	if (st->size == st->capacity)
	{
		int newsize = st->capacity == 0 ? 4 : st->capacity * 2;
		StackDataType* tmp = (StackDataType*)realloc(st->_a, sizeof(StackDataType) * newsize);
		if (tmp == NULL)
		{
			perror("realloc fail");
			exit(1);
		}
		st->_a = tmp;
		st->capacity = newsize;
	}
}

void stackPush(Stack* st, StackDataType x)
{
	assert(st);
	checkCapacity(st);
	st->_a[st->size++] = x;
}

StackDataType stackTop(Stack* st)
{
	assert(st);
	assert(!stackIsEmpty(st));
	return st->_a[st->size - 1];
}

StackDataType stackPop(Stack* st)
{
	StackDataType ret = stackTop(st);
	st->size--;
	return ret;
}
